from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from rest_framework.decorators import api_view

from common import services
from common.PageResult import page
from common.services import GenericModelService
from mh.models import Article
from utils.response_utils import ResponseUtils

ArticleService = GenericModelService(Article)


# 分页查询
def paginated_articles(request):
    articles = Article.objects.all()
    paginated_data = page(articles, request)
    return ResponseUtils.success_response(data=paginated_data)


@api_view(['POST'])
def add_article(request):
    # 假设请求数据是 JSON 格式
    data = request.POST

    title = request.data.get('title')
    content = request.data.get('content')
    topic_id = request.data.get('topic_id')
    user_id = request.data.get('user_id')

    if not all([title, content, topic_id]):
        return ResponseUtils.json_response(code=400, message='缺少必要参数')

    try:
        # 调用 create_object 方法创建 Article 对象
        new_article = ArticleService.create_object(
            title=title,
            content=content,
            topic_id=topic_id,
            user_id=user_id,
        )

        if new_article:
            return ResponseUtils.success_response(data={
                'id': new_article.id,
                'title': new_article.title,
                'content': new_article.content,
                'author': new_article.topic_id,
            })
        else:
            return ResponseUtils.json_response(code=500, message='创建文章失败')
    except Exception as e:
        return ResponseUtils.json_response(code=500, message=f'创建文章时出现错误: {str(e)}')
